package coco.wx.com.module.user.service.impl;

import cn.hutool.http.HttpUtil;
import coco.wx.com.exception.BizException;
import coco.wx.com.module.user.entity.User;
import coco.wx.com.module.user.mapper.UserMapper;
import coco.wx.com.module.user.service.UserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Preconditions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author srx
 * @since 2020-10-23
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 小程序ID
     */
    @Value("${wechat.program.app-id}")
    private String appId;

    /**
     * 小程序密钥
     */
    @Value("${wechat.program.secret}")
    private String secret;

    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseEntity<Object> wxLogin(String code) {

        Map<String, Object> resultMap = new HashMap<>();
        String loginUrl = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, secret, code);
        // 创建http GET请求
        String result = HttpUtil.get(loginUrl, 1000 * 10);
        if (result == null) {
            throw new BizException("请求微信授权失败~！");
        }
        JSONObject jsObj = JSONObject.parseObject(result);
        String wxOpenid = jsObj.getString("openid");
        String sessionKey = jsObj.getString("session_key");
        //得到微信openID
        if (StringUtils.isEmpty(wxOpenid)) {
            throw new BizException("未获取到openid~！");
        }

        //根据id数据库数据查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", wxOpenid);
        User user = userMapper.selectOne(queryWrapper);
        // 如果user等于null说明该用户第一次登录，数据库没有该用户信息。
        if (user == null) {
            resultMap.put("openId", wxOpenid);
            resultMap.put("sessionKey", sessionKey);
        } else {
            resultMap.put("openId", wxOpenid);
            resultMap.put("sessionKey", sessionKey);
            resultMap.put("user", user);
        }
        return ResponseEntity.ok().body(resultMap);
    }

    @Override
    public ResponseEntity<Object> getWxUserInfo(String openId, String accessToken) {

        if (StringUtils.isEmpty(accessToken)) {
            throw new BizException("accessToken参数缺失！");
        }
        if (StringUtils.isEmpty(openId)) {
            throw new BizException("openId参数缺失！");
        }
        String urlFormat = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=%s";
        String url = String.format(urlFormat, accessToken, openId, "zh_CN");
        String res = HttpUtil.get(url);

        if (StringUtils.isBlank(res)) {
            throw new BizException("获取微信用户信息失败！");
        }
        return ResponseEntity.ok().body(JSONObject.parseObject(res));
    }

    @Override
    public ResponseEntity<Object> getUserAccountInfo(User dto) {

        Preconditions.checkNotNullOrEmpty(String.valueOf(dto.getUserId()), "参数userId不能为空");
        return ResponseEntity.ok().body(userMapper.selectById(dto.getUserId()));
    }
}
